package l2ft.gameserver.templates.item;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ExistingItems
{
	private static ExistingItems _instance;
	private int[] _existingItems;
	
	public ExistingItems()
	{
		loadExistingItems();
	}
	
	public boolean shouldIdExist(int id)
	{
		boolean shouldExist = false;
		for(int i = 0;i<_existingItems.length;i++)
			if(_existingItems[i] == id)
				shouldExist = true;
		return shouldExist;
	}
	
	private void loadExistingItems()
	{
		List<Integer> allItems = new ArrayList<Integer>();
		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = docBuilderFactory.newDocumentBuilder();
            Document doc = db.parse(new File("data/xml/other/existing_items.xml"));
            
            NodeList list = doc.getElementsByTagName("item");
			for (int i = 0; i < list.getLength(); i++) {
				Element element = (Element) list.item(i);
				String id = element.getAttribute("id");
				allItems.add(Integer.parseInt(id));
		  	}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		_existingItems = new int[allItems.size()];
		int i = 0;
		for(Integer id : allItems){
			_existingItems[i] = id;
			i++;
		}
	}
	
	public static ExistingItems getInstance()
	{
		if(_instance == null)
			_instance = new ExistingItems();
		return _instance;
	}
}
